// 上传接口配置
const UPLOAD_BASE_URL = 'http://106.53.192.143:2774';
const UPLOAD_ENDPOINT = '/best-live-boot/common/file/upload';

// 上传响应接口
interface UploadResponse {
  msg: string;
  code: number;
  data: {
    fileName: string;
    originalName: string;
    fileUrl: string;
    fileSize: number;
    contentType: string;
    scene: string;
    uploadTime: string;
  };
}

/**
 * 上传文件到服务器
 * @param file 要上传的文件
 * @param scene 场景标识，如 'HOUSE_IMAGE'
 * @param source 来源标识，默认 'PC'
 * @returns Promise<UploadResponse['data']>
 */
export const uploadFile = async (
  file: File,
  scene: string,
  source: string = 'PC',
): Promise<UploadResponse['data']> => {
  try {
    const formData = new FormData();
    formData.append('source', source);
    formData.append('scene', scene);
    formData.append('file', file);

    const response = await fetch(`${UPLOAD_BASE_URL}${UPLOAD_ENDPOINT}`, {
      method: 'POST',
      body: formData,
      mode: 'cors', // 允许跨域
      headers: {
        // 不设置 Content-Type，让浏览器自动设置 multipart/form-data
        // 'Content-Type': 'multipart/form-data',
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result: UploadResponse = await response.json();

    if (result.code !== 200) {
      throw new Error(result.msg || '上传失败');
    }

    if (!result.data?.fileUrl) {
      throw new Error('上传失败：未返回文件URL');
    }

    return result.data;
  } catch (error) {
    console.error('上传文件失败:', error);
    throw error;
  }
};

/**
 * 上传房屋图片
 * @param file 图片文件
 * @returns Promise<UploadResponse['data']>
 */
export const uploadHouseImage = async (
  file: File,
): Promise<UploadResponse['data']> => {
  return uploadFile(file, 'HOUSE_IMAGE');
};

/**
 * 批量上传文件
 * @param files 文件列表
 * @param scene 场景标识
 * @param source 来源标识
 * @returns Promise<UploadResponse['data'][]>
 */
export const uploadMultipleFiles = async (
  files: File[],
  scene: string,
  source: string = 'PC',
): Promise<UploadResponse['data'][]> => {
  try {
    const uploadPromises = files.map((file) => uploadFile(file, scene, source));
    const results = await Promise.all(uploadPromises);
    return results;
  } catch (error) {
    console.error('批量上传文件失败:', error);
    throw error;
  }
};

/**
 * 检查文件类型
 * @param file 文件对象
 * @param allowedTypes 允许的文件类型
 * @returns boolean
 */
export const checkFileType = (
  file: File,
  allowedTypes: string[] = ['image/jpeg', 'image/png', 'image/gif'],
): boolean => {
  return allowedTypes.includes(file.type);
};

/**
 * 检查文件大小
 * @param file 文件对象
 * @param maxSize 最大文件大小（MB）
 * @returns boolean
 */
export const checkFileSize = (file: File, maxSize: number = 5): boolean => {
  const sizeInMB = file.size / (1024 * 1024);
  return sizeInMB <= maxSize;
};
